<template>
  <div class="login">
    <el-form
      v-show="isLogin"
      :model="loginForm"
      status-icon
      :rules="ruleLoginForm"
      ref="loginForm"
      label-width="100px"
      class="demo-ruleForm"
    >
      <h2>登录</h2>
      <el-form-item label="用户名" prop="username">
        <el-input v-model="loginForm.username"></el-input>
      </el-form-item>
      <el-form-item label="密码" prop="password">
        <el-input
          type="password"
          v-model="loginForm.password"
          autocomplete="off"
        ></el-input>
      </el-form-item>
      <el-form-item>
        <el-button width="300px" type="primary" @click="submitForm('loginForm')"
          >登录</el-button
        >
        <el-button @click="goRegister">注册</el-button>
      </el-form-item>
    </el-form>

    <!-- 注册页面 -->
    <el-form
      v-show="!isLogin"
      :model="registerForm"
      status-icon
      :rules="ruleRegister"
      ref="registerForm"
      label-width="100px"
      class="demo-ruleForm"
    >
      <h2>注册</h2>
      <el-form-item label="用户名" prop="username">
        <el-input v-model="registerForm.username"></el-input>
      </el-form-item>
      <el-form-item label="密码" prop="password">
        <el-input
          type="password"
          v-model="registerForm.password"
          autocomplete="off"
        ></el-input>
      </el-form-item>
      <el-form-item label="确认密码" prop="checkPass">
        <el-input
          type="password"
          v-model="registerForm.checkPass"
          autocomplete="off"
        ></el-input>
      </el-form-item>
      <el-form-item label="邮箱" prop="email">
        <el-input v-model="registerForm.email" autocomplete="off"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleRegisterForm('registerForm')"
          >注册</el-button
        >
        <el-button @click="resetForm('registerForm')">重置</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import axios from "axios";
export default {
  name: "Login",
  mixins: [],
  components: {},
  props: {},
  data() {
    var checkUsername = (rule, value, callback) => {
      if (!value) {
        return callback(new Error("用户名不能为空"));
      }
      callback();
    };
    var validatePass = (rule, value, callback) => {
      if (!value) {
        callback(new Error("请输入密码"));
      } else {
        if (this.registerForm.checkPass !== "") {
          this.$refs.registerForm.validateField("checkPass");
        }
        callback();
      }
    };
    var validatePass2 = (rule, value, callback) => {
      if (!value) {
        callback(new Error("请再次输入密码"));
      } else if (value != this.registerForm.password) {
        callback(new Error("两次输入密码不一致!"));
      } else {
        callback();
      }
    };
    return {
      isLogin: true,
      randomUrl: "",
      loginForm: {
        username: "",
        password: "",
      },
      registerForm: {
        username: "",
        password: "",
        checkPass: "",
        email: "",
      },
      ruleLoginForm: {
        password: [{ validator: validatePass, trigger: "blur" }],
        username: [
          { validator: checkUsername, trigger: "blur" },
          {
            min: 1,
            max: 20,
            message: "用户名不能超过20字",
            trigger: "blur",
          },
        ],
      },
      ruleRegister: {
        password: [{ validator: validatePass, trigger: "blur" }],
        checkPass: [{ validator: validatePass2, trigger: "blur" }],
        username: [
          { validator: checkUsername, trigger: "blur" },
          {
            min: 1,
            max: 20,
            message: "用户名不能超过20字",
            trigger: "blur",
          },
        ],
      },
    };
  },
  computed: {},
  watch: {},
  created() {},
  mounted() {},
  methods: {
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          axios({
            url: "/user/login",
            method: "post",
            data: this.loginForm,
          }).then((res) => {
            const data = { ...res.data };
            if (data.code == 200) {
              localStorage.setItem("user", JSON.stringify(data.data));
              this.$message.success("登录成功");
              this.$router.push("/user");
            } else {
              this.$message.error(data.msg);
            }
          });
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
    handleRegisterForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          axios({
            url: "/user/register",
            method: "post",
            data: {
              username: this.registerForm.username,
              password: this.registerForm.password,
              email: this.registerForm.email,
              image: this.randomUrl,
            },
          }).then((res) => {
            const data = { ...res.data };
            console.log(data);
            if (data.code == 200) {
              this.$message.success("注册成功");
              this.resetForm(formName);
              this.isLogin = true;
            } else {
              this.$message.error(data.msg);
            }
          });
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    goRegister() {
      this.isLogin = false;
      this.resetForm("registerForm");
      this.randomAvatar();
    },
    randomAvatar() {
      const config = {
        method: "get",
        url: "https://api.btstu.cn/sjtx/api.php",
        params: {
          lx: "b1",
          format: "json",
        },
        responseType: "json",
      };
      axios(config)
        .then((res) => {
          this.randomUrl = res.data.imgurl;
        })
        .catch((err) => {
          this.$message.error(err.message);
        });
    },
  },
};
</script>

<style lang="css">
h2 {
  color: rgb(92, 88, 88);
  text-align: center;
}

.login .el-form {
  width: 400px;
  margin: 100px auto 0;
}
</style>
